﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：PurchaseGoodsSelect.cs
    // 文件功能描述：勾选采购目录
    // 创建标识：吕海乐2009-05-13
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using System.Data;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Hospitals.Procurement
{
    public partial class PurchaseGoodsSelect : BasePage
    {
        public PurchaseGoodsSelect()
        {
            this.ModuleNo = Module.制定采购目录.ToString();
            this.PageOperateType = OperateType.入围.ToString();
        }

        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
        IBLL_HospitalProcureCatalog ihp = Factory.BLL_HospitalProcureCatalog();
        IBLL_CustomGoods icg = Factory.BLL_CustomGoods();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            if (!IsPostBack)
            {
                //绑定所有项目
                //ProcurementProject procurementProject = new ProcurementProject();
                //procurementProject.ProcureStartTimeFrom = Convert.ToDateTime("1890-01-01");
                //procurementProject.ProcureStartTimeTo = Convert.ToDateTime("2099-12-31");
                //procurementProject.ProcureEndTimeFrom = Convert.ToDateTime("2000-01-01");
                //procurementProject.ProcureEndTimeTo = Convert.ToDateTime("2099-12-31");
                //int temp;
                //IList<ProcurementProject> projectList = ipb.GetProjectByWhere(procurementProject, 1, 0, out temp);
                //ddlProject.DataSource = projectList;
                //ddlProject.DataTextField = "ProjectName";
                //ddlProject.DataValueField = "ProjectID";
                //ddlProject.DataBind();
                //ListItem item = new ListItem();
                //item.Text = Constants.ALL_ITEM_TEXT;
                //item.Value = Constants.ALL_ITEM_VALUE;
                //ddlProject.Items.Insert(0, item);

                setBind();
                //若没有可选产品，将选择按钮隐藏
                if (gvwProduceCatalog.Rows.Count <= 0)
                {
                    btnAdd.Visible = false;
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            //setBind();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            setBind();
        }

        /// <summary>
        /// 绑定所有符合条件的采购目录
        /// </summary>
        private void setBind()
        {
            //获取查询条件(前提条件：此采购目录可用 否则医疗机构无法看到此采购目录)
            Model.Query.HospitalProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.HospitalProcureCatalog();
            procureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.GoodsID = txtGoodsId.Text.Trim();
            procureCatalog.Companyname_Sc = txtProduceCompany_SC.Text.Trim();
            //procureCatalog.PackUnit = this.txtPackUnit.Text.Trim().ToUpper();
            //procureCatalog.MedicineModelName = txtMedicineModel.Text.Trim();
            procureCatalog.Outlookc = HZ.Fun.CheckString(txtOutLook.Text.Trim());
            //procureCatalog.Pack = txtPack.Text.Trim();
            procureCatalog.PinyinCode = this.txtpinyincode.Text.Trim();
            procureCatalog.QualityLevel = this.txtQualityLevel.Text.Trim();
            //procureCatalog.ProductName = txtProductName.Text.Trim();
            procureCatalog.GoodsName = HZ.Fun.CheckString(txtGoodsName.Text.Trim());
            procureCatalog.Unit = HZ.Fun.CheckString(txtUnit.Text.Trim());
            procureCatalog.Material = HZ.Fun.CheckString(txtMaterial.Text.Trim());
            procureCatalog.IsUsing = true;
            if (this.ddlProjectid.Visible != false)
            {
                procureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                procureCatalog.ProjectID = "0001";
            }
            //string orgID = CurrentAccount.GetUser().Org.OrgID;
            //bool flag = ipb.GetIsJiCeng(orgID);//判断是否基层医疗机构 add by zdc
            //if (flag)//盟市添加的只能采购基本药物和内蒙基本药物 zdc
            //{
            //    procureCatalog.IsJiCeng = 0;
            //}
            //procureCatalog.Companyname_Tb = txtCompany_TB.Text;
            //if (ucIsBasicRemedy1.SelectValue != -1) procureCatalog.IsBasicRemedy = ucIsBasicRemedy1.SelectValue;   

            procureCatalog.SortFields = " GoodsName asc,goodsid asc";

            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            IList<Model.View.ProcureCatalog> procureCatalogList = ihp.GetProcureCatalogNotInCurrentCatalog(procureCatalog, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwProduceCatalog.DataSource = procureCatalogList;
            gvwProduceCatalog.DataBind();
            if (totalCount > 0)
            {
                gvwProduceCatalog_Check();
            }
        }
        /// <summary>
        /// 检验该产品是否可采购
        /// </summary>
        protected void gvwProduceCatalog_Check()
        {
            string strGoodsIDs = "''";
            for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
            {
                strGoodsIDs += ",'" + gvwProduceCatalog.DataKeys[i].Values[1].ToString() + "'";
            }
            Model.Query.CustomGoods model = new HZ.DrugTrade.Model.Query.CustomGoods();
            model.Append = " goodsid in (" + strGoodsIDs + ")";
            model.SortFields = " goodsid asc";
            int total = 0;
            IList<HZ.DrugTrade.Model.View.CustomGoods> lst = icg.GetCustomGoodsByWhere(model, 1, 0, out total);
            if (lst != null && lst.Count > 0)
            {
                int rowCount = gvwProduceCatalog.Rows.Count;

                foreach (HZ.DrugTrade.Model.View.CustomGoods item in lst)
                {
                    for (int i = 0; i < rowCount; i++)
                    {
                        if (item.GoodsId == gvwProduceCatalog.DataKeys[i].Values[1].ToString() && item.AllowHospitalIDS.ToUpper().Contains(CurrentAccount.GetUser().Org.OrgID) == false)
                        {
                            ((CheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1")).Enabled = false;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 简单查询与高级查询间的转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                txtMaterial.Text = "";
                txtGoodsId.Text = "";
                txtProduceCompany_SC.Text = "";
                //txtPackUnit.Text = "";
                txtUnit.Text = "";
                txtQualityLevel.Text = "";
            }
        }

        /// <summary>
        /// 将选择的目录存入医疗机构采购目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            List<HospitalProcureCatalog> hospitalCatalogList = new List<HospitalProcureCatalog>();


            for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                if (chk.Checked == true)
                {
                    HospitalProcureCatalog catalog = new HospitalProcureCatalog();
                    catalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
                    catalog.ProcureCatalogID = gvwProduceCatalog.DataKeys[i].Values[0].ToString();
                    catalog.IsUsing = true;
                    hospitalCatalogList.Add(catalog);
                }
            }
            if (hospitalCatalogList.Count > 0)
            {
                //调取方法，保存所选的采购目录 
                if (ihp.AddHospitalProcureCatalog_Batch(hospitalCatalogList) == 1)
                {

                    HZ.Web.WebUtil.Alert("保存成功！", this);
                    setBind();
                }
                else
                {
                    PageError("保存失败！", this.ReturnUrl);
                }
            }
            else
            {
                HZ.Web.WebUtil.Alert("请至少选择一个采购目录！", this);
            }


            ////获取所有选择的目录
            //string ids = Request["checkbox1"];
            //if (!string.IsNullOrEmpty(ids))
            //{
            //    string[] arrayID = ids.Split(',');
            //    foreach (string item in arrayID)
            //    {
            //        HospitalProcureCatalog catalog = new HospitalProcureCatalog();
            //        catalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            //        catalog.ProcureCatalogID = item;
            //        catalog.IsUsing = true;
            //        hospitalCatalogList.Add(catalog);
            //    }

            //    //调取方法，保存所选的采购目录 
            //    if (ihp.AddHospitalProcureCatalog_Batch(hospitalCatalogList)==1)
            //    {
            //        setBind();
            //    }
            //    else
            //    {
            //        PageError("保存失败！", this.ReturnUrl);
            //    }
            //}
            //else
            //{
            //    HZ.Web.WebUtil.Alert("请至少选择一个采购目录！",this);
            //}
        }

        /// <summary>
        /// 关闭选择页面，跳转至设置配送企业页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFinish_Click(object sender, EventArgs e)
        {
            HZ.Web.WebUtil.RedirectByScript("PurchaseGoodsSetCompany.aspx");
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            Model.Query.HospitalProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.HospitalProcureCatalog();
            //procureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.GoodsID = txtGoodsId.Text.Trim();
            procureCatalog.Companyname_Sc = txtProduceCompany_SC.Text.Trim();
            //procureCatalog.PackUnit = this.txtPackUnit.Text.Trim().ToUpper();
            procureCatalog.Outlookc = HZ.Fun.CheckString(txtOutLook.Text.Trim());
            procureCatalog.PinyinCode = this.txtpinyincode.Text.Trim();
            if (this.ddlProjectid.Visible != false)
            {
                procureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                procureCatalog.ProjectID = "0001";
            }
            procureCatalog.QualityLevel = this.txtQualityLevel.Text.Trim();
            procureCatalog.GoodsName = HZ.Fun.CheckString(txtGoodsName.Text.Trim());
            procureCatalog.Unit = HZ.Fun.CheckString(txtUnit.Text.Trim());
            procureCatalog.Material = HZ.Fun.CheckString(txtMaterial.Text.Trim());
            procureCatalog.IsUsing = true;
            procureCatalog.Append = string.Format(" ProcureCatalogID NOT IN (SELECT ProcureCatalogID FROM TB_HospitalProcureCatalog WHERE HospitalID = '{0}') ", CurrentAccount.GetUser().Org.OrgID);
            procureCatalog.SortFields = " GoodsName asc,goodsid asc";
            //int totalCount = 0;
            //IList<Model.View.ProcureCatalog> procureCatalogList = ihp.GetProcureCatalogNotInCurrentCatalog(procureCatalog, 1, 0, out totalCount);
            //System.Data.DataTable tb = HZ.Data.ModelConvert.GetDataTableFromModel(procureCatalogList);
            //HZ.Excel.ExcelHelper.ExportDataForWeb(tb, gvwProduceCatalog);
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.HospitalProcureCatalog>(procureCatalog, true);
            string sql = "";
            if (this.ddlProjectid.Visible != false)
            {
                sql = string.Format(@"SELECT '‘'||Goodsid 产品编号,sortname 目录名称,GoodsName 产品名称,Outlookc 规格型号,Material 材质,Count 最小包装数量,Unit 最小计量单位,CompanyName_SC_TB 生产企业代理,QualityLevel 产品类别,ProcurePrice 自主报价,ProjectName 项目 FROM View_ProcureCatalog_tb  WHERE 1=1 {0}", where);
            }
            else
            {
                sql = string.Format(@"SELECT Goodsid 产品编号,sortname 目录名称,GoodsName 产品名称,Outlookc 规格型号,Material 材质,Count 最小包装数量,Unit 最小计量单位,CompanyName_SC_TB 生产企业代理,QualityLevel 产品类别,ProcurePrice 采购限价,ProjectName 项目 FROM View_ProcureCatalog_tb  WHERE 1=1 {0}", where);
            }
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "采购目录.xls");
        }

        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (ddlProjectid.SelectedItem.Value == "0002")
                {
                    e.Row.Cells[e.Row.Cells.Count - 4].Text = "自主报价";
                }
                else
                {
                    e.Row.Cells[e.Row.Cells.Count - 4].Text = "采购限价";
                }
            }
        }

    }
}
